package com.gzyj.flink.gps.map.updatetp;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.gzyj.flink.driver.Driverlogininfo;
import com.gzyj.flink.gps.GPSPosition;
import com.gzyj.flink.gps.config.RedisKeyPrefixConfig;
import com.gzyj.flink.gps.factory.RedisSessionFactory;
import com.gzyj.flink.gps.utils.IntUtils;
import com.gzyj.flink.pojo.gps.Tpvehdata;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.text.SimpleDateFormat;
import java.util.Date;

public class UpdateTpDataProcess extends RichMapFunction<GPSPosition, Tpvehdata> {

    LettuceConnectionFactory redisFactory;

    private RedisTemplate<String, Object> getRedisTemplate(LettuceConnectionFactory redisSessionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisSessionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new FastJsonRedisSerializer<>(Object.class));
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new FastJsonRedisSerializer<>(Object.class));
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    public Driverlogininfo TryGetData_DLD(String vehId, RedisTemplate<String, Object> clusterRedisTemplate) {
        Object obj = clusterRedisTemplate.opsForValue().get(RedisKeyPrefixConfig.RedisKey_DriverSignOn + vehId);
        if (obj == null) {
            return new Driverlogininfo();
        } else {
            return JSON.parseObject(JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect), Driverlogininfo.class);
        }

    }


    @Override
    public void open(Configuration parameters) throws Exception {
        redisFactory = RedisSessionFactory.getRedisFactory();
    }

    @Override
    public Tpvehdata map(GPSPosition gpsPosition) throws Exception {
        RedisTemplate<String, Object> clusterRedisTemplate = getRedisTemplate(redisFactory);
        Tpvehdata result = null;
        try {

            double Lon = gpsPosition.getLngExt();
            double Lat = gpsPosition.getLatExt();
            int Speed = gpsPosition.getSpeedExt();
            int Direction = gpsPosition.getDIRECTION();
            int Locate = IntUtils.LocalExt(gpsPosition.getSTATUSBIT());
            String Alarmnote = gpsPosition.getAlarmNoteExt();
            int AlarmFlag = (StringUtils.isNotEmpty(Alarmnote) ? 1 : 0);
            Date dateTime = gpsPosition.getGPSTimeExt();
            int Mile = gpsPosition.MileageExt();
            Integer Oil = gpsPosition.OilExt();
            int ACC = IntUtils.AccExt(gpsPosition.getSTATUSBIT());
            Integer Signal = gpsPosition.SignalExt();
            Integer SatelliteLen = gpsPosition.SatelliteLenExt();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Driverlogininfo driverlogininfo=TryGetData_DLD(gpsPosition.getVehId(),clusterRedisTemplate);

            if (!clusterRedisTemplate.hasKey(RedisKeyPrefixConfig.RedisKey_TpData + gpsPosition.getTerminalPhoneNo())) {

                //新车刚开始进来的时候
                Tpvehdata tpVehData = new Tpvehdata();
                tpVehData.setVehid(gpsPosition.getVehId());
                tpVehData.setDeviceid(gpsPosition.getTerminalPhoneNo());
                tpVehData.setVenumber(gpsPosition.getCheliangpaizhao());
                tpVehData.setVecolor(gpsPosition.getChepaiyanse());
                tpVehData.setDeptid(String.valueOf(gpsPosition.getDeptId()));
                tpVehData.setCheliangzhuangtai(gpsPosition.getCheliangzhuangtai());
                tpVehData.setShiyongxingzhi(gpsPosition.getShiyongxingzhi());
                tpVehData.setDriverName(driverlogininfo.getDriverName());
                tpVehData.setMileZongduan(Mile);
                tpVehData.setLongitude(Lon);
                tpVehData.setLatitude(Lat);
                tpVehData.setVelocity(Speed);
                tpVehData.setAngle(Direction);
                tpVehData.setLocate(Locate);
                tpVehData.setOil(Oil);
                tpVehData.setAcc(ACC);
                tpVehData.setWifisignal(Signal);
                tpVehData.setSatellitelen(SatelliteLen);

                if (Locate == 1) {
                    tpVehData.setLastlocatetime(new Date());
                } else {
                    if (tpVehData.getLastlocatetime() == null)
                        tpVehData.setLastlocatetime(new DateTime("2021-01-01 00:00:00", "yyyy-MM-dd HH:mm:ss").toJdkDate());
                }
                tpVehData.setTime(dateTime);
                tpVehData.setSystime(new Date());
                tpVehData.setAlarm(AlarmFlag);
                tpVehData.setAlarmnote(Alarmnote);

                if (ACC > 0 && Speed == 0) {
                    //通电速度为0
                    tpVehData.setStartStop(true);
                    tpVehData.setStoptime(sdf.format(dateTime));
                    tpVehData.setFlameout(0);
                } else if (ACC > 0 && Speed > 0) {
                    tpVehData.setStartStop(false);
                    tpVehData.setStoptime(null);
                    tpVehData.setFlameout(0);
                } else if (ACC == 0) {
                    //断电了
                    tpVehData.setStartStop(true);
                    tpVehData.setStoptime(sdf.format(dateTime));
                    tpVehData.setFlameout(0);
                }

                clusterRedisTemplate.opsForValue().set(RedisKeyPrefixConfig.RedisKey_TpData + gpsPosition.getTerminalPhoneNo(), tpVehData);
                result=tpVehData;
            } else {
                Object obj = clusterRedisTemplate.opsForValue().get(RedisKeyPrefixConfig.RedisKey_TpData + gpsPosition.getTerminalPhoneNo());
                Tpvehdata old = JSON.parseObject(JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect), Tpvehdata.class);

                if (dateTime.getTime() >= old.getTime().getTime()) {
                    //保证最新数据
                    old.setLongitude(Lon);
                    old.setLatitude(Lat);
                    old.setVelocity(Speed);
                    old.setAngle(Direction);
                    old.setLocate(Locate);
                    old.setOil(Oil);
                    old.setDriverName(driverlogininfo.getDriverName());
                    old.setAcc(ACC);
                    old.setMileZongduan(Mile);
                    old.setWifisignal(Signal);
                    old.setSatellitelen(SatelliteLen);
                    if (Locate == 1) {
                        old.setLastlocatetime(new Date());
                    } else {
                        if (old.getLastlocatetime() == null)
                            old.setLastlocatetime(new DateTime("2021-01-01 00:00:00", "yyyy-MM-dd HH:mm:ss").toJdkDate());
                    }
                    long startTime = old.getTime().getTime();
                    long endTime = dateTime.getTime();
                    long diffTime = Math.abs(endTime - startTime);
                    long diffDays = diffTime / (24 * 60 * 60 * 1000);
                    if(diffDays>0){
                        old.setMileToday(0.0);
                    }
                    old.setTime(dateTime);
                    old.setSystime(new Date());
                    old.setAlarm(AlarmFlag);
                    old.setAlarmnote(Alarmnote);

                    if (ACC > 0 && Speed > 0) {
                        //运行
                        old.setStartStop(false);
                        old.setStoptime(null);
                        old.setFlameout(0);
                    } else if (ACC > 0 && Speed == 0) {
                        if (old.getStartStop() != null && old.getStartStop()) {
                            long ts = dateTime.getTime() - new DateTime(old.getStoptime(), "yyyy-MM-dd HH:mm:ss").toJdkDate().getTime();
                            old.setFlameout(Long.valueOf(ts / 1000).intValue());
                        } else if (old.getStartStop() == null|| old.getStartStop()==false) {
                            //首次停车
                            old.setStartStop(true);
                            old.setStoptime(sdf.format(dateTime));
                            old.setFlameout(0);
                        }
                    } else if (ACC == 0) {
                        //断电了
                        if (old.getStartStop() != null && old.getStartStop()) {
                            long ts = dateTime.getTime() - new DateTime(old.getStoptime(), "yyyy-MM-dd HH:mm:ss").toJdkDate().getTime();
                            old.setFlameout(Long.valueOf(ts / 1000).intValue());
                        } else if (old.getStartStop() == null|| old.getStartStop()==false) {
                            //首次停车
                            old.setStartStop(true);
                            old.setStoptime(sdf.format(dateTime));
                            old.setFlameout(0);
                        }


                    }


                    clusterRedisTemplate.opsForValue().set(RedisKeyPrefixConfig.RedisKey_TpData + gpsPosition.getTerminalPhoneNo(), old);
                    result=old;
                }


            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return result;
        }
    }
}
